﻿using System;
using System.Collections.Generic;
using System.ServiceModel.DomainServices.Client;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Navigation;
using AppLab.Models;
using AppLab.Web;
using AppLab.Web.Services;

namespace AppLab.Views
{
    public partial class History : Page
    {
        private IList<OperationBase> possiblyPendingOperations = new List<OperationBase>();
        FlowContext flow = new FlowContext();
        private HistoryData history = new HistoryData();
        /// <summary>
        /// 控制每页DateGrid的行数
        /// </summary>
        private const int pageSize = 6;

        public History()
        {
            InitializeComponent();
            PageScrollViewer.SetIsMouseWheelScrollingEnabled(true);
            this.Title = ApplicationStrings.HistoryPageTitle;
            this.DataContext = history;
        }

        // Executes when the user navigates to this page.
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            busyIndicatorLoad.IsBusy = true;

            BindMobileBrand();
            BindAllMobileType();

            BindMbBasicGrid(-1, 0);
        }

        #region DataGrid:终端基本信息
        /// <summary>
        /// brandID 小于0，表示没有对品牌做条件
        /// </summary>
        /// <param name="brandID"></param>
        private void BindMbBasicGrid(int brandID, int pageIndex)
        {
            LoadItemsSource(brandID, pageIndex, string.Empty);
        }

        private void BindMbBasicGrid(string type, int pageIndex)
        {
            LoadItemsSource(-1, pageIndex, type);
        }

        private void LoadItemsSource(int brandID, int pageIndex, string type)
        {
            InvokeOperation<int> iCount = flow.GetMobileBasicInfoCount(brandID, type);
            iCount.Completed += new EventHandler(iCount_Completed);

            var temp = flow.GetMobileBasicInfoOnPageQuery(pageSize, pageIndex, brandID, type);
            LoadOperation<MobileBasicInfoData> loadMb = flow.Load(temp);
            loadMb.Completed += new EventHandler(loadMb_Completed);
        }

        void loadMb_Completed(object sender, EventArgs e)
        {
            LoadOperation loadMb = (LoadOperation)sender;
            dgPhoneInfo.ItemsSource = loadMb.Entities;

            if (loadMb.TotalEntityCount > 0)
            {
                
                dgPhoneInfo.SelectedIndex = 0;
                this.VersionsOfMobileGrid.IsHitTestVisible = true;
            }
            else
            {
                this.VersionsOfMobileGrid.IsHitTestVisible = false;
                this.VersionInfoGrid.IsHitTestVisible = false;
                this.TipsForMobileVersion.Text = ApplicationStrings.TipsForNoMobileRecord;
            }

            busyIndicatorLoad.IsBusy = false;
        }

        void iCount_Completed(object sender, EventArgs e)
        {
            InvokeOperation invokeOp = (InvokeOperation)sender;
            if (dpPhoneInfo.PageIndex <= 0)
            {
                dpPhoneInfo.BindSource((int)(invokeOp.Value), pageSize);
                dpPhoneInfo.PageIndexChanged -= new EventHandler<EventArgs>(dpPhoneInfo_PageIndexChanged);
                dpPhoneInfo.PageIndexChanged += new EventHandler<EventArgs>(dpPhoneInfo_PageIndexChanged);
            }
        }

        private void dpPhoneInfo_PageIndexChanged(object sender, EventArgs e)
        {
            //左右换页时，默认让其选中第一行
            if (mobileBrand.SelectedItem == null && string.IsNullOrEmpty(autoCompleteBoxMbBrand.Text))
            {
                BindMbBasicGrid(-1, dpPhoneInfo.PageIndex);
            }
            else if (mobileBrand.SelectedItem != null)
            {
                BindMbBasicGrid((mobileBrand.SelectedItem as Brand).BrandId, dpPhoneInfo.PageIndex);
            }
            else
            {
                BindMbBasicGrid(autoCompleteBoxMbBrand.Text.Replace(" ", ""), dpPhoneInfo.PageIndex);
            }
        }
        #endregion

        #region DataGrid：版本信息
        //第一次加载(dpVersionInfo.PageIndex =-1): The PageIndex Property can only be set to -1 
        //                                    when the source property is null or the pagesixe property is 0.
        //以后,重新加载：PageIndex must be greater than or equal to 0.
        private bool iVerson1 = true;
        private void dgPhoneInfo_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            MobileBasicInfoData emp = dgPhoneInfo.SelectedItem as MobileBasicInfoData;
            if (emp != null && emp.MobileID != 0)
            {
                this.TipsForMobileVersion.Text = emp.MobileBrand + "(" + emp.MobileType + ")" + ApplicationStrings.TipsForMobileVersion;

                dpVersionInfo.PageIndex = iVerson1 ? -1 : 0;
                BindVersionsDataGrid(emp.MobileID, 0);
            }
            iVerson1 = false;
        }

        //绑定各种版本信息
        private void BindVersionsDataGrid(int mobileID, int pageIndex)
        {
            busyIndicatorLoad.IsBusy = true;
            InvokeOperation<int> VCount = flow.GetMobileVersionsCount(mobileID);
            VCount.Completed += new EventHandler(VCount_Completed);

            var temp = flow.GetVersionsDataGridQuery(mobileID, pageSize, pageIndex);
            LoadOperation<HistoryData> loadVs = flow.Load(temp);
            loadVs.Completed += new EventHandler(loadVs_Completed);
        }

        void VCount_Completed(object sender, EventArgs e)
        {
            InvokeOperation invokeOp = (InvokeOperation)sender;
            if (dpVersionInfo.PageIndex <= 0)
            {
                dpVersionInfo.BindSource((int)(invokeOp.Value), pageSize);
                dpVersionInfo.PageIndexChanged -= new EventHandler<EventArgs>(dpVersionInfo_PageIndexChanged);
                dpVersionInfo.PageIndexChanged += new EventHandler<EventArgs>(dpVersionInfo_PageIndexChanged);
            }
        }

        void loadVs_Completed(object sender, EventArgs e)
        {
            LoadOperation loadVs = (LoadOperation)sender;
            this.dgPhoneAllVersionInfo.ItemsSource = loadVs.Entities;

            //如果该型号的版本信息不存在，隐藏详细信息
            if (loadVs.TotalEntityCount > 0)
            {
                this.dgPhoneAllVersionInfo.SelectedIndex = 0;
                this.VersionInfoGrid.IsHitTestVisible = true;
            }
            else
            {
                this.VersionInfoGrid.IsHitTestVisible = false;
            }
            busyIndicatorLoad.IsBusy = false;
        }

        void dpVersionInfo_PageIndexChanged(object sender, EventArgs e)
        {
            MobileBasicInfoData emp = dgPhoneInfo.SelectedItem as MobileBasicInfoData;
            if (emp != null && emp.MobileID != 0)
            {
                BindVersionsDataGrid(emp.MobileID, dpVersionInfo.PageIndex);
            }
        }

        private void dgPhoneAllVersionInfo_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            HistoryData emp = dgPhoneAllVersionInfo.SelectedItem as HistoryData;
            if (emp != null)
            {
                this.TipsForVersionInfo.Text = emp.MoblieBrandAndType + "/" + emp.MobileVersion + ApplicationStrings.TipsForVersionInfo;
                //给出品牌手机的最新发布方式
                if (!string.IsNullOrEmpty(emp.PublishedStr))
                {
                    this.TipsForPublishedStr.Text = emp.MobileType + ApplicationStrings.PublishedMethods;
                    this.PublishedStr.Text = emp.PublishedStr;
                }
                else
                {
                    this.TipsForPublishedStr.Text = emp.MobileType + ApplicationStrings.TipsForNoPublishedMethods;
                    this.PublishedStr.Text = string.Empty;
                }

                //审核未通过，给出拒绝理由
                if (!string.IsNullOrEmpty(emp.ReviewComment))
                {
                    this.TipsForReject.IsHitTestVisible = true;
                    this.TipsForRejectCom.Text = ApplicationStrings.TipsForRejectComment;
                    this.TipsForRejectComment.Text = emp.ReviewComment;
                }
                else
                {
                    this.TipsForReject.IsHitTestVisible = false;
                }
            }
        }
        #endregion

        #region 查询操作

        private void mobileBrand_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (mobileBrand.SelectedItem != null)
            {
                this.dgPhoneAllVersionInfo.ItemsSource = null;
                this.autoCompleteBoxMbBrand.Text = string.Empty;
                this.dpPhoneInfo.PageIndex = 0;
                BindMbBasicGrid((mobileBrand.SelectedItem as Brand).BrandId, 0);
            }
        }

        private void SearchButton_Click(object sender, RoutedEventArgs e)
        {
            this.dpPhoneInfo.PageIndex = 0;
            this.mobileBrand.SelectedItem = null;
            if (string.IsNullOrEmpty(autoCompleteBoxMbBrand.Text.Replace(" ", "")))
            {
                BindMbBasicGrid(-1, 0);
            }
            else
            {
                BindMbBasicGrid(autoCompleteBoxMbBrand.Text.Replace(" ", ""), 0);
            }
        }

        private void autoCompleteBoxMbBrand_GotFocus(object sender, RoutedEventArgs e)
        {
            mobileBrand.SelectedItem = null;
        }

        private void ShowAllMobileInfo_Click(object sender, RoutedEventArgs e)
        {
            this.mobileBrand.SelectedItem = null;
            this.autoCompleteBoxMbBrand.Text = string.Empty;
            this.dpPhoneInfo.PageIndex = 0;

            BindMbBasicGrid(-1, 0);
        }
        #endregion

        #region 绑定手机品牌与手机型号

        /// <summary>
        /// 下拉框中的手机品牌
        /// </summary>
        private void BindMobileBrand()
        {
            var query = flow.GetBrandsQuery();
            var loadOp = flow.Load(query);
            // Binding the ComboBox object
            mobileBrand.ItemsSource = loadOp.Entities;
            mobileBrand.DisplayMemberPath = "BrandName";
        }

        /// <summary>
        /// AtuoComBox的手机型号
        /// </summary>
        private void BindAllMobileType()
        {
            var query = flow.GetMobileTypesQuery(-1);
            LoadOperation<MobileType> load = flow.Load(query);
            load.Completed += new EventHandler(load_Completed);
        }

        private ComboBox comb = new ComboBox();

        void load_Completed(object sender, EventArgs e)
        {
            LoadOperation loadOp = (LoadOperation)sender;
            comb.ItemsSource = loadOp.Entities;

            BindAutoCompleteBox(comb);
        }

        private void BindAutoCompleteBox(ComboBox comb)
        {
            List<String> listStr = new List<string>();
            for (int i = 0; i < comb.Items.Count; i++)
            {
                MobileType e = comb.Items[i] as MobileType;
                listStr.Add(e.TypeName);
            }
            autoCompleteBoxMbBrand.ItemsSource = listStr;
        }

        #endregion
    }
}
